package april.example.keepalive;

import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ChildChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.ChannelGroup;
import org.jboss.netty.channel.group.DefaultChannelGroup;

public class ServerHandler extends SimpleChannelHandler {
	public static final ChannelGroup channelGroup = new DefaultChannelGroup();

	public int id;

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		System.out.println("进来一个");
	}

	@Override
	public void channelDisconnected(ChannelHandlerContext ctx,
			ChannelStateEvent e) throws Exception {
		super.channelDisconnected(ctx, e);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
			throws Exception {
		Logger.getAnonymousLogger().info(e.getCause().getMessage());
		ctx.getChannel().close();
		// TODO Auto-generated method stub
		// super.exceptionCaught(ctx, e);
	}

	@Override
	public void childChannelClosed(ChannelHandlerContext ctx,
			ChildChannelStateEvent e) throws Exception {

		super.childChannelClosed(ctx, e);
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		System.out.println(this.id++);

		// google protocol解码后返回为 ChannelBuffer类型
		if (!(e.getMessage() instanceof ChannelBuffer))
			return;
		// 获得 消息对象
		ChannelBuffer channelBuffer = (ChannelBuffer) e.getMessage();

		// MessageInfo info =
		// Message.MessageInfo.newBuilder().mergeFrom(channelBuffer.copy().array()).build();
		// 写回给客户端
		e.getChannel().write(channelBuffer);

	}
}
